<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://unpkg.com/x-data-spreadsheet@1.1.9/dist/xspreadsheet.css">
    <script src="https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js"></script>

    <script src="xlsxspread.js"></script>
    <script src="./xspreadsheet.js"></script>
    <script src="zh-cn.js"></script>

</head>
<body>
<input type="file" id="fileInput">导入文件</input>
<button type="button" id="fileOutput">导出文件</button>
<button type="button" id="clearTable">清空表格</button>
<div id="xspreadsheet"></div>


<script>
    var config = {};
    x_spreadsheet.locale('zh-cn');
    const xs = x_spreadsheet('#xspreadsheet', config);
    // 导入文件处理
    document.addEventListener('DOMContentLoaded', function () {
        const fileInput = document.getElementById('fileInput');
        const fileOutputButton = document.getElementById('fileOutput');
        const clearTableButton = document.getElementById('clearTable');
        const OUTPUT_FILE_NAME = "Output.xlsx";
        // 导入文件：当文件被选中时触发
        fileInput.addEventListener('change', async function (event) {
            const files = event.target.files; // 获取选中的文件列表
            if (files.length > 0) { // 确保至少有一个文件被选中
                const file = files[0]; // 取第一个文件
                console.log("file type: " + file.type)
                // 如果文件格式不是xlsx或xls或csv
                if (file.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" &&
                    file.type !== "application/vnd.ms-excel" &&
                    file.type !== "text/csv") {
                    alert("请选择xlsx、xls或csv格式的文件");
                    return;
                }
                const ab = await (file.arrayBuffer());
                xs.loadData(stox(XLSX.read(ab)));
            }
        });
        // 导出文件
        fileOutputButton.addEventListener('click', function () {
            XLSX.writeFile(xtos(xs.getData()), OUTPUT_FILE_NAME);
        });
        // 清空表格
        clearTableButton.addEventListener('click', function () {
            xs.loadData({});
        });
    });

</script>

</body>
</html>